//
//  YZXPullRefresh.swift
//  下拉刷新
//
//  Created by 叶周翔 on 16/7/25.
//  Copyright © 2016年 叶周翔. All rights reserved.
//

import UIKit
 /// 刷新的三种状态
enum PullingRefreshStatus{
    case Normal     ///下拉刷新
    case Pulling    ///释放刷新
    case Refreshing ///正在刷新
}

class YZXPullRefresh: UIView {
    /// 下拉的高度
    private let PullingDownRefreshHeight:CGFloat = 60
    
 /// 进入下拉刷新的闭包
    var refreshingCallback:(() -> Void)?
    
    private var currentStatus: PullingRefreshStatus = PullingRefreshStatus.Normal {
        didSet{
            
            switch currentStatus{
            case PullingRefreshStatus.Normal:
                messageLabel.text = "下拉刷新"
                // 箭头的方向 不变
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowView.transform = CGAffineTransformIdentity
                })
            case PullingRefreshStatus.Pulling:
                messageLabel.text = "释放刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case PullingRefreshStatus.Refreshing:
                self.arrowView.hidden = true
                self.loadingView.hidden = false
                messageLabel.text = "正在刷新"
                // 旋转动画
                let anim = CABasicAnimation(keyPath: "transform.rotation")
                anim.toValue = 2 * M_PI
                anim.duration = 0.75
                anim.removedOnCompletion = false
                // 添加到图层上
                loadingView.layer.addAnimation(anim, forKey: nil)
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.newSuperScrollView?.contentInset.top = self.newSuperScrollView!.contentInset.top + self.PullingDownRefreshHeight
                })
                
                // 可以去加载数据
                self.refreshingCallback?()
            }
        }
    }
    
    // MARK:-在一开始的时候直接进入刷新的状态
    func beginRefreshing(){
        self.currentStatus = PullingRefreshStatus.Refreshing
    }
    
    func endRefreshing(){
        if self.currentStatus == PullingRefreshStatus.Refreshing{
            self.currentStatus = PullingRefreshStatus.Normal
            self.loadingView.layer.removeAllAnimations()
            self.loadingView.hidden = true
            self.arrowView.hidden = false
            UIView.animateWithDuration(0.25, animations: { () -> Void in
               self.newSuperScrollView?.contentInset.top = self.newSuperScrollView!.contentInset.top - self.PullingDownRefreshHeight
            })
        }
        
    }
    
    
    
    
    // MARK:初始化方法
    
    var newSuperScrollView:UIScrollView?
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        
        let newFrame = CGRect(x: 0.0, y: -PullingDownRefreshHeight, width: UIScreen.mainScreen().bounds.size.width, height: PullingDownRefreshHeight)
        super.init(frame: newFrame)
        
//        self.backgroundColor = UIColor.redColor()
        self.setUI()
        
    }
    
    //MARK:设置视图
    func setUI(){
        // 一开始的时候隐藏转轮视图
        self.loadingView.hidden = true
        
        // 
        self.arrowView.translatesAutoresizingMaskIntoConstraints = false
        self.loadingView.translatesAutoresizingMaskIntoConstraints = false
        self.messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        self.addSubview(arrowView)
        self.addSubview(loadingView)
        self.addSubview(messageLabel)
        // 设置箭头约束
        self.addConstraint(NSLayoutConstraint(item: arrowView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -15))
        self.addConstraint(NSLayoutConstraint(item: arrowView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
       
        // 设置文字内容的约束
        self.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: arrowView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        // 设置转轮的约束
        self.addConstraint(NSLayoutConstraint(item: loadingView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: arrowView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: loadingView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: arrowView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        
    }
    
    // 在即将移动到父控件中，调用addSubView后触发
    override func willMoveToSuperview(newSuperview: UIView?) {
        if newSuperview is UIScrollView {
            // 父控件可以滚动, 监听父控件的滚动
            self.newSuperScrollView = newSuperview as? UIScrollView
            
            // KVO
            self.newSuperScrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        }

    }
    
    // 移除KVO
    deinit{
        self.newSuperScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    // 实现KVO的方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if self.newSuperScrollView!.dragging{
            /**
            *  下拉刷新->释放刷新
            */
            if self.currentStatus == PullingRefreshStatus.Pulling && self.newSuperScrollView?.contentOffset.y > -124{
                
                self.currentStatus = PullingRefreshStatus.Normal
                
            }else if self.currentStatus == PullingRefreshStatus.Normal && self.newSuperScrollView?.contentOffset.y <= -124{
                
                self.currentStatus = PullingRefreshStatus.Pulling
            
            }
        }else{
            
            if self.currentStatus == PullingRefreshStatus.Pulling{
                
                self.currentStatus = PullingRefreshStatus.Refreshing
            }
        }
        
        
    }
    
    
    // MARK:懒加载控件
    // 箭头
    lazy var arrowView:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    // 正在刷新
    lazy var loadingView:UIImageView = UIImageView(image: UIImage(named: "tableview_loading"))
    // 文字内容
    lazy var messageLabel:UILabel = {
        let label:UILabel = UILabel()
        label.text = "下拉刷新"
        label.font = UIFont.systemFontOfSize(15)
        label.textColor = UIColor.darkGrayColor()
        return label
    }()
    
}
